<?php


namespace app\common\model;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Exceptions\Exception;
use think\Model;
use think\Db;

class Cart extends Model
{

    
    
    /*
     * 购物车信息
     * */
    public function indexInfo($data_array)
    {
        $url  = config('fastadmin.api_url');
        $page = $data_array['page'] ? $data_array['page'] : 1;
        $data = Db::name('user_cart')
            ->where('user_id',$data_array['user_id'])
            ->field('update_time',true)
            ->order('create_time desc')
            ->page($page,10)
            ->select();
        $goods = Db::name('goods')->where(['is_del'=>1])->column('item','id');
        if($data)
        {
            foreach($data as $key => $val)
            {
                $data[$key]['image'] = $url.$val['image'];
                $gd = isset($goods[$val['goods_id']]) ? $goods[$val['goods_id']] : "";
                if($gd)
                {
                    $item = json_decode($gd,true);
                    foreach($item as $ke => $va)
                    {
                        if($val['item'] == $va['title'])
                        {
                            $data[$key]['money'] = $va['intro'];
                        }
                    }
                }
            }
        }
        return $data;
    }

    

    /*
     * 添加到购物车
     * */
    public function adds($data_array)
    {
        // 获取商品信息
        $goods = Db::name('goods')->where('id',$data_array['goods_id'])->find();
        $image = explode(',',$goods['image']);

        $data  = ['user_id'=>$data_array['user_id'],'goods_id'=>$data_array['goods_id'],'name'=>$goods['name'],'money'=>$data_array['money'],'num'=>$data_array['num'],'image'=>$image[0],'item'=>$data_array['name']];

        $time = time();
        // 存在及更新，反之添加
        if(Db::name('user_cart')->where(['goods_id'=>$data_array['goods_id'],'user_id'=>$data_array['user_id']])->count() > 0)
        {
            $where = ['goods_id'=>$data_array['goods_id'],'user_id'=>$data_array['user_id'],'item'=>$data_array['name'],'money'=>$data_array['money']];
            if(Db::name('user_cart')->where($where)->count() > 0)
            { 
                $num = Db::name('user_cart')->where($where)->value('num');
                $cart['update_time'] = $time;
                $cart['num']         = $num + $data_array['num'];
                $res = Db::name('user_cart')->where($where)->update($cart);
            }else{
                $res = Db::name('user_cart')->insert($data);
            }

        }else{
            $data['create_time'] = $time;
            $res = Db::name('user_cart')->insert($data);
        }
        if($res)
        {
            return ['msg'=>'操作成功','data'=>'','code'=>1];
        }else{
            return ['msg'=>'操作失败','data'=>'','code'=>0];
        }

    }


    /*
     *  删除购物车
     * */
    public function dels($data_array)
    {
        
        if(empty($data_array['num']))
        {
            $res = Db::name('user_cart')->where(['id'=>$data_array['cart_id']])->delete();
        }else{
            $res = Db::name('user_cart')->where(['id'=>$data_array['cart_id']])->update(['num'=>$data_array['num']]);
        }
        if($res)
        {
            return ['msg'=>'操作成功','data'=>'','code'=>1];
        }else{
            return ['msg'=>'操作失败','data'=>'','code'=>0];
        }

    }


    /*
     * 购物车添加数量
     * */
    public function addNums($data)
    {
        $type = $data['type'];
        // type : 1 加数量，2：减数量
        if($type == 1)
        {
            $res = Db::name('user_cart')->where('id',$data['cart_id'])->setInc('num',$data['num']);
        }else{

            $res = Db::name('user_cart')->where('id',$data['cart_id'])->setDec('num',$data['num']);
        }
        if($res)
        {
            return ['msg'=>'成功','data'=>'','code'=>1];
        }else{
            return ['msg'=>'失败','data'=>'','code'=>0];
        }
        
    }


    /*
     * 购物车下单
     * */
    public function cartOrders($data)
    {
        // 调用config
        $config = config('wechat_pay');
        $app    = Factory::payment($config);
        // 获取商品信息
        $goods_id = $data['cart_id'];
        $goods    = Db::name('user_cart')->where('id','in',$goods_id)->select();
        $user  = Db::name('user')->where('id',$data['user_id'])->find();
        $order = $money = $num = [];
        // 订单编号
        $orderno = date('YmdHis', time()) . substr(microtime(), 2, 6) . sprintf('%03d', rand(0, 999));
        // 优惠券存在
        
        // 判断是否是秒杀商品
        $time       = time();
        $ms         = Db::name('goods')
            ->alias('g')
            ->join('goods_seckill gs','g.id = gs.good_id')
            ->field('g.id')
            ->where(['g.activity'=>1])
            ->where('g.start_time','<=',$time)
            ->where('g.end_time','>=',$time)
            ->column('g.id');

        if($data['cou_id'])
        {
            $couNum = Db::name('user_coupons')->where(['id'=>$data['cou_id'],'user_id'=>$data['user_id']])->value('num');
            if($couNum)
            {
                $cid= Db::name('user_coupons')->where(['id'=>$data['cou_id'],'user_id'=>$data['user_id']])->value('cou_id');
                $uc = Db::name('user_coupons')
                    ->alias('uc')
                    ->join('coupons c','uc.cou_id = c.id')
                    ->where(['c.id'=>$cid,'user_id'=>$data['user_id']])
                    ->field('uc.id,c.id as cous_id,c.full,c.reduces')
                    ->find();
            }

        }else{
            $data['cou_id'] = 0;
            $uc = 0;
        }



        // 统计出 金额 * 数量 = 总金额
        foreach($goods as $val)
        {
            
            if(in_array($val['goods_id'],$ms) && $val['num'] > 1)return ['code'=>'0','msg'=>'该商品为秒杀商品,限购数量','data'=>''];
            
            $nums = Db::name('goods')->where('id',$val['goods_id'])->value('item');
            $nums = json_decode($nums,true);
            foreach($nums as $vv)
            {
                if($val['item'] == $vv['title'])
                {
                    if($val['num'] > $vv['stock'])return ['code'=>'0','msg'=>'库存不足,请减少购买量','data'=>''];
                }
            }
            // $nums = Db::name('goods')->where('id',$val['goods_id'])->value('num');
           
            $money[] = intval($val['money'] * $val['num']);
             
            if($val['num'] == 1)
            {
                $num = 1;
            }else{
                $num = intval($val['num']);
            }
        }
        $price = "";
        $money = array_sum($money);
//        $num   = array_sum($num);
//        $price = $money * $num;

//        if($uc || $price < $uc) return ['code'=>0,'data'=>'','msg'=>'使用的优惠券未达到条件'];

        if($uc)
        {
            if($money > $uc['full']){
                $price = $money - $uc['reduces'];
            }
        }else{
            $price = $money;
        }
        
        $phone = Db::name('user_address')->where('id',$data['address_id'])->value('phone');

        // 先生成一个总订单，在生成子订单
        $countOrder = [
            'order_id'  =>  $orderno,
            'user_id'   =>  $data['user_id'],
            'username'  =>  $user['nickname'],
            'is_vip'    =>  $user['is_vip'],
            'address_id'=>  $data['address_id'],
            'cou_id'    =>  $data['cou_id'],
            'desc'      =>  $data['desc'],
            'number'    =>  $phone,
            'pid'       =>  1,// 有子集
            'money'     =>  $price,
            'price'     =>  $price,
            'num'       =>  $num,
            'order_time'  =>  time(),
            'status'    =>  1,
            'type'      =>  $data['type'],
            'create_time' => time()
        ];
        
        // type : 1: 余额支付，2：微信支付
        if($data['type'] == 1)
        {
            if($user['money'] < $price)return ['code'=>0,'msg'=>'余额不足,请换种方式支付','data'=>''];
            Db::startTrans();
            try{
                $countOrder['status'] = 2;
                // 生成订单总信息
                $getOrderId = Db::name('order')->insertGetId($countOrder);

                foreach($goods as $key => $val)
                {
                    $orders = date('YmdHis', time()) . substr(microtime(), 2, 6) . sprintf('%03d', rand(0, 999)) . $key;
                    $order[] = [
                        'order_id'    => $orders,
                        'user_id'     => $data['user_id'],
                        'username'    => $user['nickname'],
                        'is_vip'      =>  $user['is_vip'],
                        'address_id'  => $data['address_id'],
                        'goods_id'    => $val['goods_id'],
                        'number'      => $phone,
                        'name'        => $val['name'],
                        'title'       => $val['item'],
                        'money'       => $val['money'],
                        'price'       => $val['money'],
                        'num'         => $val['num'],
                        'type'        => $data['type'],
                        'cou_id'      => $data['cou_id'],// 优惠券
                        'desc'        => $data['desc'],
                        'pid'         => $getOrderId,
                        'status'      => 2,
                        'order_time'  => time(),
                        'pay_time'    => time(),
                        'create_time' => time()
                    ];
                }
                // 是会员,定期返还完金额，生成记录
                if($user['is_vip'])
                {
                    if(Db::name('user_refund_amount')->where('user_id',$data['user_id'])->count())
                    {
                        Db::name('user_refund_amount')->where('user_id',$data['user_id'])->setInc('money',$money);
                    }else{
                        $amount = ['user_id'=>$data['user_id'],'money'=>$money,'refund_amount'=>0,'create_time'=>time()];
                        Db::name('user_refund_amount')->insert($amount);
                    }
                }
                
                foreach($goods as $val)
                {
                    $item = Db::name('goods')->where('id',$val['goods_id'])->value('item');
                    $item = json_decode($item,true);
                    foreach($item as &$vv)
                    {
                        if($val['item'] == $vv['title'])
                        {
                            $vv['stock'] = $vv['stock'] - $val['num'];
                        }
                    }
                    Db::name('goods')->where('id',$val['goods_id'])->update(['item'=>json_encode($item)]);
                }
                
                $consume = ['user_id'=>$data['user_id'],'sub_user_id'=>0,'type'=>1,'status'=>2,'money'=>$countOrder['money'],'content'=>'余额购买','create_time'=>time(),'state'=>1];
                Db::name('order')->insertAll($order);
                Db::name('user')->where('id',$data['user_id'])->setDec('money',$countOrder['money']);
                Db::name('user_consume')->insert($consume);
                Db::name('user_cart')->where('id','in',$goods_id)->delete();
                Db::commit();
                return ['code'=>'1','msg'=>'购买成功','data'=>''];
            }catch(Exception $exception)
            {
                Db::rollback();
                return ['code'=>0,'msg'=>'购买失败','data'=>''];
            }
        }else{
            // 生成订单总信息
            $getOrderId = Db::name('order')->insertGetId($countOrder);

            foreach($goods as $key => $val)
            {
                $orders = date('YmdHis', time()) . substr(microtime(), 2, 6) . sprintf('%03d', rand(0, 999)) . $key;
                $order[] = [
                    'order_id'    => $orders,
                    'user_id'     => $data['user_id'],
                    'username'    => $user['nickname'],
                    'address_id'  => $data['address_id'],
                    'goods_id'    => $val['goods_id'],
                    'name'        => $val['name'],
                    'title'       => $val['item'],
                    'money'       => $val['money'],
                    'price'       => $val['money'],
                    'num'         => $val['num'],
                    'cou_id'      => $data['cou_id'],// 优惠券
                    'desc'        => $data['desc'],
                    'pid'         => $getOrderId,
                    'type'        => $data['type'],
                    'status'      => 1,
                    'order_time'    => time(),
                    'create_time' => time()
                ];
            }

            Db::name('order')->insertAll($order);

            $result = $app->order->unify([
                'body' => '充值'.$money.'元',
                'out_trade_no' => $orderno,
                // 'response_type' => 'array',
                'total_fee' => $price * 100,//测试
                'notify_url' => 'https://'.$_SERVER['HTTP_HOST'].'/api/payCall/payGoods',
                'trade_type' => 'JSAPI',
                'openid' => $user['openid'],
            ]);
            $jssdk = $app->jssdk;
            $config = $jssdk->bridgeConfig($result['prepay_id'], false);

            if ($config){
                return ['msg'=>'调用成功', 'code'=>1, 'data'=>$config];
            }else{
                return ['msg'=>'调用失败', 'code'=>0, 'data'=>''];
            }
        }

    }





}